package org.freespace.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class GlobalConf {
    private final Environment environment;
    private static Environment env;

    private static Map<String, Object> map = new HashMap<>();

    @Autowired
    private GlobalConf(Environment env) {
        this.environment = env;
    }

    @PostConstruct
    public void init(){
        env = environment;
    }

    public static String getConfig(String key) {
        Object o = map.get(key);
        String value = null;
        if (o instanceof String) {
            value = (String) o;
        }

        if (StringUtils.isEmpty(value)) {
            value = env.getProperty(key);
            map.put(key, StringUtils.isNotEmpty(value) && !"null".equals(value) ? value : "");
        }
        return StringUtils.isNotEmpty(value) && !"null".equals(value) ? value : "";
    }

    public static <T> T getConfig(String key , Class<T> clazz) {
        T value = (T) map.get(key);

        if (value == null) {
            value = env.getProperty(key,clazz);
            map.put(key, value);
        }
        return value;
    }

    public static <T> T getConfig(String key , Class<T> clazz, T defaultValue) {
        T value = (T) map.get(key);

        if (value == null) {
            value = env.getProperty(key,clazz, defaultValue);
            map.put(key, value);
        }
        return value;
    }
}
